package com.ershi.interceptor;

import com.ershi.result.Result;
import com.ershi.util.CommonUtil;
import com.ershi.util.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户微服务模块登陆拦截器
 *
 * @author yinhuidong3@xiaomi.com
 * @since 2021/7/21
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<TokenUtil.LoginUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String token = request.getHeader("token");
        try {
            if (token == null){
                token = request.getParameter("token");
            }

            if (StringUtils.isNotBlank(token)){
                Claims claims = TokenUtil.checkJWT(token);
                if (claims==null){
                    // tell the login is expire , please retry to login !
                    CommonUtil.sendJsonMessage(response, Result.buildError("登录过期，请重新登录！"));
                    return false;
                }
                //获取参数
                Long id =Long.valueOf(claims.get("id").toString());

                String headImg = (String) claims.get("head_img");

                String mail = (String) claims.get("mail");

                String name = (String) claims.get("name");

                //用户信息传递
                threadLocal.set(new TokenUtil.LoginUser(id,headImg,mail,name));
                return true;
            }
        } catch (NumberFormatException e) {
            log.error("登陆拦截器出错，错误原因：{ }",e);
        }

        CommonUtil.sendJsonMessage(response, Result.buildError("token不存在，请重新登录！"));

        return false;
    }
}
